<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />
    <!-- 操作按钮区域 -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        :border='true'
        :resizable='true'
        :showOverflow='true'
        size='mini'
        :loading='loading'
        :height='pageHeight-seachHeight-94'
        :align='left'
        :columns='columns'
        :data='dataSource'
        :toolbar-config="tableToolbar"
       :checkbox-config="checkboxConfig"
        v-bind='vexConfig'
        @checkbox-change='selectChangeEvent'
        @checkbox-all="selectChangeEvent"
      >
        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button v-has="'minoq:add'" @click='handleAdd'>新增</a-button>
            <a-button v-has="'minoq:delete'" @click='batchDel'>删除</a-button>
            <a-button v-has="'minoq:synchronization'" @click="downExportXls('cnProduct_service')">同步</a-button>
            <a-button v-has="'minoq:export'" @click="downExportXls('cnProduct_service' )">导出</a-button>
          </div>
        </template>

        <template #detail='{ row,rowIndex }'>
          <a style='color: #1890FF' @click='handleAdd(row,"详情",true,true)'>{{ row.pupCode }}</a>
        </template>

        <template #updateStatus='{ row }'>
          <a-switch :checked='row.status' size='small' @change='handleStatus(row,$event)' />
        </template>

        <template #action='{ row }'>
          <a v-has="'minoq:update'" @click='handleAdd(row,"编辑")'>编辑</a>
          <a-divider type='vertical' />
          <a v-has="'business:log'" href='javascript:;' @click='handleBusiness("最小起订量",row)'>日志</a>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync='ipagination.current'
            :page-size.sync='ipagination.pageSize'
            :total='ipagination.total'
            :pageSizes='ipagination.pageSizeOptions'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>

    <!-- table区域-begin -->
    <form-add-edit ref='formAdd' @ok='modalFormOk'></form-add-edit>
    <business-log ref='businessLog'></business-log>
  </a-card>
</template>

<script>
  import { getProductCategory } from '@/api/api'
  import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
  import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
  import JInput from '@/components/cn-form/JInput.vue'
  import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import Vue from 'vue'
  import { filterObj } from '@/utils/util'
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  import { getAction } from '@/api/manage'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import search from '@comp/view/base-crud/search/Search'
  export default {
    name: 'product-list',
    mixins: [PageListMixin],
    components: {
      FormAddEdit,
      JSuperQuery,
      JInput,
      JTreeSelect,
      search
    },
    data() {
      return {
        selectedRowKeys: [],
        description: '最小起订量',
        importExcelUrl: window._CONFIG['domianURL'] + '/minorderquantity/cnMinOrderQuantity/findPageList',
        searchConfig: [
          {
            // label:'订单编号',
            type: 'input',
            name: 'pupCode',
            placeholder: '提货点编号'
          },
          {
            // label:'订单编号',
            type: 'input',
            name: 'productCode',
            placeholder: '产品编号'
          },
          {
            // label:'订单编号',
            type: 'input',
            name: 'productName',
            placeholder: '产品名称'
          },
          {
            type: 'a-select',
            name: 'status',
            placeholder: '请选择状态',
            option: [
              {
                name:'启用',
                value:1
              },
              {
                name: '停用',
                value:0
              }]
          }
        ],
        //表头
        columns: [],
        //列设置
        settingColumns: [],
        //列定义
        defColumns: [
          { type: 'checkbox', width: 60, fixed: 'left' },

          {
            title: '提货点编号',
            align: 'center',
            field: 'pupCode',
            fixed: 'left',
            ellipsis: true,
            slots: {
              default: 'detail'
            },
            minWidth: 80,
          },
          {
            title: '提货点名称',
            align: 'left',
            ellipsis: true,
            field: 'pupName',
            minWidth: 80,
          },
          {
            title: '最小起订量',
            align: 'left',
            ellipsis: true,
            field: 'minOrderQuantity',
            minWidth: 80,
          },
          {
            title: '产品编号',
            align: 'left',
            ellipsis: true,
            field: 'productCode',
            minWidth: 80,
          },
          {
            title: '产品名称',
            align: 'left',
            ellipsis: true,
            field: 'productName',
            minWidth: 80,
          },
          {
            title: '备注',
            align: 'left',
            ellipsis: true,
            field: 'remarks',
            minWidth: 80,
          },
          {
            title: '创建人',
            align: 'left',
            ellipsis: true,
            field: 'createName',
            minWidth: 80,
          },
          {
            title: '创建时间',
            align: 'left',
            ellipsis: true,
            field: 'createTime',
            minWidth: 80,
          },
          {
            title: '更新人',
            align: 'left',
            ellipsis: true,
            field: 'updateName',
            minWidth: 80,
          },
          {
            title: '更新时间',
            align: 'left',
            ellipsis: true,
            field: 'updateTime',
            minWidth: 80,
          },
          {
            title: '状态',
            align: 'center',
            field: 'action',
            fixed: 'right',
            minWidth: 80,
            slots: {
              // filterIcon: 'filterIcon',
              default: 'updateStatus'
            }
          },
          {
            title: '操作',
            field: 'action',
            fixed: 'right',
            align: 'center',
            minWidth: 120,
            slots: {
              default: 'action'
            }
          }
        ],
        url: {
          list: '/minorderquantity/cnMinOrderQuantity/findPageList',
          delete: '/minorderquantity/cnMinOrderQuantity/delete',
          detail: '/minorderquantity/cnMinOrderQuantity/saveOrUpdate',
          deleteBatch: '/minorderquantity/cnMinOrderQuantity/deleteBatch',
          exportXlsUrl: window._CONFIG['domianURL'] + '/cnProductController/exportXls',
          deleteTag: '/cnTerminalController/deleteLabels',
          saveOrUpdateTag: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateLabels',
          startOrStopUrl: window._CONFIG['domianURL'] + '/minorderquantity/cnMinOrderQuantity/startOrStop',
          // 导入接口
          importExcelUrl: window._CONFIG['domianURL'] + '/cnProductController/importExcel'
        },
      }
    },
    created() {
      this.initColumns()
    },
    methods: {
      startorstop: function(status) {
        if (!this.url.startOrStopUrl) {
          this.$message.error('请设置url启用停用!')
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
          return
        } else {
          var ids = ''
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ','
          }
          var that = this
          this.$confirm({
            title: '确认修改',
            content: '是否修改选中数据?',
            onOk: function() {
              that.loading = true
              getAction(that.url.startOrStopUrl, { ids: ids, status: status }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.loading = false
              })
            }
          })
        }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      getQueryParams() {
        //高级查询器
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

        param.field = this.getQueryField()
        param.current = this.ipagination.current
        param.size = this.ipagination.pageSize
        delete param.birthdayRange //范围参数不传递后台
        return filterObj(param)
      },



      //列设置更改事件
      onColSettingsChange(checkedValues) {
        var key = this.$route.name + ':colsettings'
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (this.settingColumns.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      },

      initColumns() {
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name + ':colsettings'
        let colSettings = Vue.ls.get(key)
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = []
          this.defColumns.forEach(function(item, i, array) {
            allSettingColumns.push(item.field)
          })
          this.settingColumns = allSettingColumns
          this.columns = this.defColumns
        } else {
          this.settingColumns = colSettings
          const cols = this.defColumns.filter(item => {
            if (item.key == 'rowIndex' || item.field == 'action') {
              return true
            }
            if (colSettings.includes(item.field)) {
              return true
            }
            return false
          })
          this.columns = cols
        }
      },
      startorstopByid(status,id){
        let that=this
        this.$confirm({
          title: "确认修改",
          content: '是否'+(status==0?'停用':'启动')+'选中数据？',
          onOk(){
            that.loading = true;
            getAction(that.url.startOrStopUrl, {ids: id, status: status}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          },
          onCancel(){
            // that.loadData();
            // that.onClearSelected();
          },
        })
      },
      changeStatus(e,item){

        if(e){
          this.startorstopByid(1,item.id)
        }else{
          this.startorstopByid(0,item.id)
        }
      },
      async handleAdd(record={},title='新增',disabled=false,disableSubmit=false) {
        if (record.id && this.url.detail) {
          const res = await getAction(this.url.detail, { id: record.id })
          if (res.success) {
            if (res.result) {
              record = res.result
            }
          }
        }
        let config = {
          title: title,
          width: 500,
          addOrUpdateUrl: `${window._CONFIG['domianURL']}/minorderquantity/cnMinOrderQuantity/saveOrUpdate`,  //审核地址
          method: 'post',
          list: [
            {
              label: '产品编号',
              type: 'input-search',
              name: 'productCode',// 后台接受字段
              code:'productName',
              status:'Products',
              placeholder: '产品编号',
              disabled: disabled,
              check: { rules: [{ required: true, message: '请填写产品编号', whitespace: true }] },
              formconfig : [
                {
                  key: 'goodsCode',
                  label: '商品编号'
                },
                {
                  key: 'goodsName',
                  label: '商品名称'
                }
              ],
              tableconfig:{
                columns: [
                  {
                    title: '商品编号',
                    align: 'center',
                    dataIndex: 'goodsCode',
                    width: 120,
                    ellipsis: true
                  },
                  {
                    title: '商品名称',
                    align: 'center',
                    dataIndex: 'goodsName',
                    width: 120,
                    ellipsis: true
                  }
                ],
                list: window._CONFIG['domianURL'] + '/goods/cnGoods/findPageList',
                multiple: false,
                columW: 8,
                name:'商品'
              }
            },
            {
              label: '产品名称',
              type: 'input',
              name: 'productName',  // 后台接受字段
              placeholder: '产品名称',
              disabled: true,
              // check: { rules: [{ required: true, message: '请输入package路径',whitespace:true }] }
            },
            {
              label: '提货点编号',
              type: 'input-search',
              name: 'pupCode',  // 后台接受字段
              code: 'pupName',
              placeholder: '提货点编号',
              disabled: disabled,
              status:'Pickuppoint',
              formconfig : [
                {
                  key: 'pupCode',
                  label: '提货点编号'
                },
                {
                  key: 'goodsName',
                  label: '提货点名称'
                }
              ],
              tableconfig:{
                columns: [
                  {
                    title: '提货点编号',
                    align: 'center',
                    dataIndex: 'pupCode',
                    width: 120,
                    ellipsis: true
                  },
                  {
                    title: '提货点名称',
                    align: 'center',
                    dataIndex: 'pupName',
                    width: 120,
                    ellipsis: true
                  }
                ],
                list: window._CONFIG['domianURL'] + '/pupconfig/cnPupConfig/findPageList',
                multiple: false,
                columW: 8,
                name:'提货点'
              }
              // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
            },
            {
              label: '提货点名称',
              type: 'input',
              placeholder: '提货点名称',
              disabled: true,
              name: 'pupName'  // 后台接受字段
              // check: { rules: [{ required: true, message: '代码生成表对象集合',whitespace:true }] }
            },
            {
              label: '最小起订量',
              type: 'input-number',
              disabled:disabled,
              min:'0',
              placeholder: '最小起订量',
              name: 'minOrderQuantity',  // 后台接受字段
            },
            {
              label: '备注',
              type: 'textarea',
              placeholder: '备注',
              disabled:disabled,
              name: 'remarks',  // 后台接受字段
              // check: { rules: [{ required: true, message: '备注' }] },
            },
          ]
        }
        this.$refs.formAdd.edit(record,config )
        this.$refs.formAdd.disableSubmit = disableSubmit
      },
    },

  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>